package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.atguigu.spzx.manager.excel.CategoryReadListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;


@Service
public class CategoryServiceImpl implements CategoryService{


    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    CategoryReadListener categoryReadListener;


    @Override
    public List<Category> findByParentId(Long parentId) {

        //SELECT * FROM `category` WHERE parent_id = ? AND is_deleted = 0
        List<Category> list = categoryMapper.findByParentId(parentId);

        //对于查询出来的数据库 进行是否有下级菜单的判断
        list.forEach(category -> {

            //方式2：
            category.setHasChildren(category.getChildrenCount()>0);

            //方式1：
            //判断当前分类是否存在下级
            //SELECT COUNT(1) FROM `category` WHERE parent_id = ? AND is_deleted = 0
//            Integer count = categoryMapper.countByParentId(category.getId());
//            category.setHasChildren(count>0);

            //方式3：
//            int size = categoryMapper.findByParentId(category.getId()).size();
//            category.setHasChildren(size>0);

        });
        return list;
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public void importData(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();//获取目标文件对应的输入流

            //ReadListener categoryReadListener = null;
            EasyExcel.read(inputStream, CategoryExcelVo.class,categoryReadListener)
                    .sheet("全部商品分类").doRead();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    }

